﻿using AutoUpdaterDotNET;
using B.MESUI.Login.LoginDtos;
using DevExpress.XtraWaitForm;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net.Http;
using System.Reflection;
using System.Text;
using System.Windows.Forms;

namespace B.MESUI.Login
{
    public partial class Login : DevExpress.XtraEditors.XtraForm
    {
        public Login()
        {
            InitializeComponent();
            this.StartPosition = FormStartPosition.CenterScreen;
            AutoUpdater.CheckForUpdateEvent += AutoUpdaterOnCheckForUpdateEvent; // 只绑定一次
        }
        /// <summary>
        /// 登录方法
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void simpleButton1_Click(object sender, EventArgs e)
        {
            var request = new LoginRequest
            {
                Username = textEdit1.Text.Trim(),
                Password = textEdit2.Text.Trim()
            };

            var json = JsonConvert.SerializeObject(request);
            var content = new StringContent(json, Encoding.UTF8, "application/json");

            using (var client = new HttpClient())
            {
                try
                {
                    var response = await client.PostAsync("http://39.103.49.30:8972/api/Login/login", content);
                    var responseBody = await response.Content.ReadAsStringAsync();

                    if (response.IsSuccessStatusCode)
                    {
                        //将responseBody中的resultdata解析为LoginDto

                        // 假设后端返回结构如下：
                        var result = JsonConvert.DeserializeObject<ApiResult>(responseBody);

                        // ✅ 存储登录信息到全局 Session
                        AppSession.UserId = result.resultData.id;
                        AppSession.Username = result.resultData.userName;
                        AppSession.LoginTime = DateTime.Now;
                        MessageBox.Show("登录成功！");
                        // 打开主界面
                        var mainForm = new MainMenu();
                        mainForm.Show();
                        this.Hide();
                    }
                    else
                    {
                        MessageBox.Show($"登录失败：{responseBody}");
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show($"发生错误：{ex.Message}");
                }
            }
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            // ... 其他代码 ...
            AutoUpdater.InstalledVersion = Assembly.GetExecutingAssembly().GetName().Version;
            AutoUpdater.Start("http://39.103.49.30:9980/Update.xml");
            AutoUpdater.ShowSkipButton = true;
            AutoUpdater.ShowRemindLaterButton = true;
            // 不要再绑定事件
            CheckForUpdates();
        }

        private void CheckForUpdates()
        {
            try
            {
                // 设置更新服务器地址
                AutoUpdater.Start("http://39.103.49.30:9980/Update.xml");
                // 不要再绑定事件
            }
            catch (Exception ex)
            {
                MessageBox.Show($"检查更新时出错: {ex.Message}", "更新错误",
                    MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void AutoUpdaterOnCheckForUpdateEvent(UpdateInfoEventArgs args)
        {
            if (args != null && args.IsUpdateAvailable)
            {
                try
                {
                    if (args.Mandatory.Value)
                    {
                        // 强制更新
                        if (MessageBox.Show(
                            $"发现新版本 {args.CurrentVersion}。此更新为强制更新。是否立即更新?",
                            "更新可用", MessageBoxButtons.YesNo, MessageBoxIcon.Information) == DialogResult.Yes)
                        {
                            TryUpdate(args);
                        }
                        else
                        {
                            MessageBox.Show("应用程序将关闭，因为需要安装强制更新。", "强制更新",
                                MessageBoxButtons.OK, MessageBoxIcon.Warning);
                            Application.Exit();
                        }
                    }
                    else
                    {
                        // 可选更新
                        if (MessageBox.Show(
                            $"发现新版本 {args.CurrentVersion}。是否更新?",
                            "更新可用", MessageBoxButtons.YesNo, MessageBoxIcon.Information) == DialogResult.Yes)
                        {
                            TryUpdate(args);
                        }
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show($"更新过程中出错: {ex.Message}", "更新错误",
                        MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            else
            {
                // 已是最新版本
                MessageBox.Show("已是最新版本", "更新检查", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }

        private void TryUpdate(UpdateInfoEventArgs args)
        {
            try
            {
                if (AutoUpdater.DownloadUpdate(args))
                {
                    Application.Exit();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"下载更新时出错: {ex.Message}", "更新错误",
                    MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        // 手动检查更新按钮事件处理
        private void btnCheckUpdate_Click(object sender, EventArgs e)
        {
            CheckForUpdates();
        }

    }
}
